import React, { useState, useEffect } from 'react';
import { Table } from 'antd';

interface IState {
    loading: boolean;
    pagination: {
        current: number;
        pageSize: number;
        total: number;
    };
    dataSource: any[];
}
const useAsyncTable = (columns: any[], queryAction: any, params?: any, listName?: any) => {
    const stateInitial = {
        // 初始数据
        loading: false,
        pagination: {
            current: 1,
            pageSize: 10,
            total: 0,
        },
        dataSource: [],
    };
    const [state, setState] = useState<IState>(stateInitial);
    /** 获取表格数据 */
    const getTableData = () => {
        const { current, pageSize } = state.pagination;
        queryAction({
            ...params,
            current,
            pageSize,
        }).then((res: any) => {
            console.table(res.list);
            res.list = res.list.map((item: any, index: number) => {
                item.index = index + 1 + (current - 1) * 10
                return item
            })
            setState({
                ...state,
                dataSource: listName ? res[listName] : res.list,
                pagination: {
                    pageSize,
                    current,
                    total: res.totalCount,
                },
            });
        });
    };
    useEffect(() => {
        // if (params && JSON.stringify(params) !== JSON.stringify(state.query)) {
        //     setState({
        //        ...state,
        //        query: {
        //            ...params
        //        } 
        //     })
        //     console.log(state)
        // }
        getTableData();
    }, [params, state.pagination.current, state.pagination.pageSize]);

    /** 分页变化 */
    const handleTableChange = (pagination: any) => {
        const { current, pageSize } = pagination;
        setState({
            ...state,
            pagination: {
                ...state.pagination,
                current,
                pageSize,
            },
        });
    };

    return (
        <Table
            columns={columns}
            rowKey={(record) => record.id}
            pagination={state.pagination}
            dataSource={state.dataSource}
            loading={state.loading}
            onChange={handleTableChange}
        ></Table>
    );
};
export default useAsyncTable;
